//
//  AlbumPermissionsManager.swift
//  LeTu
//
//  Created by gy on 2023/11/24.
//

import Foundation
import UIKit
import AVFoundation
import Photos
import AssetsLibrary
import AppTrackingTransparency
import AdSupport

let kAlbumPermissionsManager = AlbumPermissionsManager.manager

class AlbumPermissionsManager: NSObject {

    static let manager = AlbumPermissionsManager()
    
    //MARK: ----获取相册权限
    static func authorizePhotoWith(comletion: @escaping (Bool) -> Void) {
        let granted = PHPhotoLibrary.authorizationStatus()
        switch granted {
        case PHAuthorizationStatus.authorized:
            comletion(true)
        case PHAuthorizationStatus.denied, PHAuthorizationStatus.restricted:
            comletion(false)
        case PHAuthorizationStatus.notDetermined:
            PHPhotoLibrary.requestAuthorization({ status in
                DispatchQueue.main.async {
                    comletion(status == PHAuthorizationStatus.authorized)
                }
            })
        default:
            comletion(false)
        }
    }
    
    //MARK: ----获取麦克风权限
    static func authorizeMicphoneWith(comletion: @escaping (Bool) -> Void) {
        let granted = AVCaptureDevice.authorizationStatus(for: .audio)
        switch granted {
        case .authorized:
            comletion(true)
        case .restricted, .denied:
            comletion(false)
        case .notDetermined:
            // 检查麦克风是否有权限
            AVCaptureDevice.requestAccess(for: .audio) { granted in
                if Thread.current != .main {
                    DispatchQueue.main.async {
                        comletion(granted)
                    }
                } else {
                    comletion(granted)
                }
            }
        default:
            comletion(false)
        }
    }
    
    //MARK: ---相机权限
    static func authorizeCameraWith(completion: @escaping (Bool) -> Void) {
        let granted = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        switch granted {
        case .authorized:
            completion(true)
        case .denied:
            completion(false)
        case .restricted:
            completion(false)
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted: Bool) in
                if Thread.current != .main {
                    DispatchQueue.main.async {
                        completion(granted)
                    }
                } else {
                    completion(granted)
                }
            })
        @unknown default:
            completion(false)
        }
    }
    
    // MARK: - 同时获取麦克风和相机权限
    static func authorizeCameraAndMicphoneWith(completion: @escaping (Bool,(title: String, msg: String)) -> Void) {
        
        let appName = Device.getAppName()
        AlbumPermissionsManager.authorizeCameraWith { status in

            if (!status) {
                completion(false,("相机权限未开启","请在“设置-\(appName)”中，允许应用访问你的相机。"))
            } else {

                AlbumPermissionsManager.authorizeMicphoneWith { granted in
                    if (!granted) {
                        completion(false,("麦克风权限未开启","请在“设置-\(appName)”中，允许应用访问你的麦克风。"))
                    } else {
                        completion(true,("",""))
                    }
                }
            }
            
        }
    }
    
    //MARK: 跳转到APP系统设置权限界面
    static func jumpToSystemPrivacySetting() {
        guard let appSetting = URL(string: UIApplication.openSettingsURLString) else {
            return
        }
        
        if UIApplication.shared.canOpenURL(appSetting as URL) {
            
            if #available(iOS 10, *) {
                UIApplication.shared.open(appSetting, options: [:], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(appSetting)
            }
            
        }
    }
    // 相机未设置权限弹框
    static func unAuthorizeAlert(vc: UIViewController, title: String, message: String) {
        
        DispatchQueue.main.async {
            
            AppAlertController(title: title, message: message, leftTitle: "取消".localized, rightTitle: "前往".localized, rightHolder:  {
                jumpToSystemPrivacySetting()
            }).show()
        }
        
    }
    
}

// MARK: - 通知是否打开权限
extension AlbumPermissionsManager {
    
    func checkPushNotification(comletion: @escaping (Bool) -> Void){

            if #available(iOS 10.0, *) {
                UNUserNotificationCenter.current().getNotificationSettings(){ (setttings) in

                    switch setttings.authorizationStatus{
                    case .authorized:

                        MYLog("enabled notification setting")
                        comletion(true)
                    case .denied:

                        MYLog("setting has been disabled")
                        comletion(false)
                    case .notDetermined:

                        MYLog("something vital went wrong here")
                        comletion(false)
                    case .provisional:
                        comletion(false)
                    case .ephemeral:
                        comletion(false)
                    @unknown default:
                        comletion(false)
                    }
                }
            } else {

                let isNotificationEnabled = UIApplication.shared.currentUserNotificationSettings?.types.contains(UIUserNotificationType.alert)
                if isNotificationEnabled == true{

                    MYLog("enabled notification setting")
                    comletion(true)

                }else{

                    MYLog("setting has been disabled")
                    comletion(false)
                }
            }
        }
    
}

// MARK: - IDFA权限
extension AlbumPermissionsManager {
    
    static func loadLocalIdfa() {
        
        if #available(iOS 14, *) {

            if UserDefaults.standard.value(forKey: "ASIdentifierAdvertisingIdentifierKey") == nil {
                ATTrackingManager.requestTrackingAuthorization { status in
                    DispatchQueue.main.async {
                        if status == .authorized {
                            let idfa = ASIdentifierManager.shared().advertisingIdentifier
                            let idfaString = idfa.uuidString
                            UserDefaults.standard.setValue(idfaString, forKey: "ASIdentifierAdvertisingIdentifierKey")
                        } else {
                            MYLog("用户拒绝了广告跟踪权限")
                        }
                    }
                }
            }

        } else {
            //UserDefaults.standard.setValue(KeychainItem.currentUserIdentifier, forKey: "ASIdentifierAdvertisingIdentifierKey")
        }
        
    }
    
    static func getIdfa() -> String? {
        return UserDefaults.standard.value(forKey: "ASIdentifierAdvertisingIdentifierKey") as? String
    }
    
}

